/**
 * @Author: lena
 * @Description:将日志打印在控制台
 * @Version: 1.0.0
 * @Date: 2021/9/7 12:55
 */

package logger

import (
	"fmt"
	"runtime"
	"time"
)

// 当前日志级别
type Logger struct {
	Level int8
}

// 构造方法
func NewLogger(level int8) Logger {
	return Logger{Level: level}
}

// 设置当前日志级别
func (this *Logger) SetLogger(level int8) {
	this.Level = level
}

// 实现Log接口中的方法
func (this Logger) Debug(msg string) {
	this.printLog(DEBUG, msg)
}
func (this Logger) TRACE(msg string) {
	this.printLog(TRACE, msg)
}
func (this Logger) INFO(msg string) {
	this.printLog(INFO, msg)
}
func (this Logger) WARNING(msg string) {
	this.printLog(WARNING, msg)
}
func (this Logger) ERROR(msg string) {
	this.printLog(ERROR, msg)
}
func (this Logger) FATAL(msg string) {
	this.printLog(FATAL, msg)
}

// 根据日志级别输出日志信息：日志输出到控制台
func (this Logger) printLog(level int8, msg string) {
	var l string
	switch level {
	case DEBUG:
		l = "DEBUG"
	case TRACE:
		l = "TRACE"
	case INFO:
		l = "INFO"
	case WARNING:
		l = "WARNING"
	case ERROR:
		l = "ERROR"
	case FATAL:
		l = "FATAL"
	}
	// 当前级别大于日志级别才输出 否则不输出
	if level >= this.Level {
		_, file, line, ok := runtime.Caller(2)
		if !ok {
			fmt.Printf("[%s] [%s] [%s:%d] %s\n", time.Now().Format("2006-01-02 15:04:05"), "ERROR", file, line, "runtime.Caller() fail")
			return
		}
		// 日志信息输出到控制台
		fmt.Printf("[%s] [%s] [%s:%d] %s\n", time.Now().Format("2006-01-02 15:04:05"), l, file, line, msg)
	}
}

/*func main() {
	my:=logger.Logger{}
	my.Level=logger.TRACE	// 设置日志级别
	for{
		my.Debug("这是一条Debug信息")
		time.Sleep(time.Second)
		my.TRACE("这是一条Trace信息")
		time.Sleep(time.Second)
		my.INFO("这是一条Info信息")
		time.Sleep(time.Second)
		my.WARNING("这是一条Warning信息")
		time.Sleep(time.Second)
		my.ERROR("这是一条Error信息")
		time.Sleep(time.Second)
		my.FATAL("这是一条Fatal信息")
		time.Sleep(time.Second)
	}
}*/
